<?php
class DiyAction extends Action {
	var $postParam = array ();
	function __construct() {
		if (isset ( $_POST )) {
			$this->postParam = $this->getPostParam ();
		}
	}
	function getPostParam() {
		foreach ( $_POST as $key => $vo ) {
			if (strpos ( $key, 'PARAM_' ) !== false) {
				$key = str_replace ( 'PARAM_', '', $key );
				$param [$key] = $vo;
			}
		}
		if (isset ( $_POST ['diyType'] )) {
			$param ['diyType'] = $_POST ['diyType'];
		}
		if (isset ( $_POST ['offset'] )) {
			$param ['offset'] = $_POST ['offset'];
		}
		if (isset ( $_POST ['image'] )) {
			$param ['image'] = $_POST ['image'];
		}
		
		return $param;
	}
	public function index() {
		$this->display ();
	}
	function detail() {
		$map ['id'] = intval ( $_REQUEST ['id'] );
		
		$info = M ( 'ad' )->where ( $map )->find ();
		
		$this->assign ( 'info', $info );
		
		$this->display ();
	}
	function setting() {
		$diyType = t ( $_REQUEST ['diyType'] );
		$diyType = ucfirst ( $diyType );
		
		$html = LIB_PATH . 'Plugins/' . $diyType . '/setting.html';
		$this->display ( $html );
	}
	function saveModel() {
		$sizeWidth = intval ( $this->postParam ['sizeWidth'] );
		$sizeHeight = intval ( $this->postParam ['sizeHeight'] );
		
		$data ['pageId'] = 1;
		$data ['attr'] = serialize ( $this->postParam );
		M ( 'diy_widget' )->add ( $data );
		
		$html = $this->_getImageHtml ();
		
		$result ['html'] = '<div style="background-color:#F00; width:' . $sizeWidth . 'px; height:' . $sizeHeight . 'px;">' . $html . '</div>';
		
		echo json_encode ( $result );
	}
	function _getImageHtml() {
		$image = $this->postParam ['image'];
		$html = '';
		
		foreach ( $image as $key => $vo ) {
			if (! empty ( $vo ['url'] )) {
				$html .= "<a href='$vo[url]'  target='_blank'>";
			}
			
			$src = SITE_URL.$vo[path];
			$html .= "<img id=$key src='$src' />";
			
			if (! empty ( $vo ['url'] )) {
				$html .= "</a>";
			}
		}
		
		return $html;
	}
}